package tt.dz.order.util.thirdrecord;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.stereotype.Component;

import tt.dz.order.pojo.YouBeiPayCallBackRecord;
import tt.dz.order.util.OrderConstant.OrderPayChannelCode;
import tt.dz.order.util.ThreadSafeDateFormat;
import tt.dz.order.vo.ThdPayWayRecord;

/**
 *
 * 
 * @name ubei第三方支付查询
 * @author Anson
 * @version 1.0
 * @summary 通过订单号查询第三方的支付记录
 * @desc
 *
 */
@Component
public class YouBeiPayThirdRecordQuery extends AbstractCommonThirdRecordQuery {

	@Override
	public OrderPayChannelCode getThirdChannelCode() {
		return OrderPayChannelCode.youbeipay;
	}

	@Override
	public List<ThdPayWayRecord> query(List<String> orderNos) {
		List<YouBeiPayCallBackRecord> originalRecords = this.queryAliPayRecord(orderNos);
		List<ThdPayWayRecord> records = new ArrayList<ThdPayWayRecord>(0);
		if (originalRecords == null || originalRecords.isEmpty()) {
			return records;
		}
		ThdPayWayRecord record = null;
		for (YouBeiPayCallBackRecord r : originalRecords) {
			record = new ThdPayWayRecord();
			record.setOrderNo(r.getOrderNo());
			record.setTradeNo(r.getTradeNo());
			record.setTradeStatus(r.getTradeStatus());
			record.setPayAmount(r.getTotalFee());
			record.setPayChannelCode(this.getThirdChannelCode().value());
			record.setQuantity(null);
			record.setFinishTime( ThreadSafeDateFormat.format(r.getCreateTime(),ThdPayWayRecord.TIME_FMT));
			records.add(record);
		}

		return records;
	}

	@SuppressWarnings("unused")
	private String fmtDate(String orginalDateFmt) {
		String fmt = "";
		Date dt = null;

		List<String> fmts = dateTryFmt();

		for (String s : fmts) {
			try {
				dt = ThreadSafeDateFormat.parse(orginalDateFmt, s);
				if (dt != null) {
					break;
				}
			} catch (ParseException e) {
			}
		}
		if (dt == null) {
			return fmt;
		}
		fmt = ThreadSafeDateFormat.format(dt, ThdPayWayRecord.TIME_FMT);
		return fmt;
	}

	private List<String> dateTryFmt() {
		List<String> list = new ArrayList<String>();
		list.add(ThdPayWayRecord.TIME_FMT);
		list.add("yyyyMMddHHmmss");
		list.add("yyyy/MM/dd HH:mm:ss");
		return list;
	}

	/**
	 * 根据订单号查询回调信息
	 * 
	 * @param orderNos
	 * @return
	 */
	public List<YouBeiPayCallBackRecord> queryAliPayRecord(List<String> orderNos) {
		return YouBeiPayCallBackRecord.getByIds(orderNos);
	}
}
